import os
import re
import base64
import json
from pathlib import Path

MIME_TYPES = {
    '.css': 'text/css',
    '.js': 'text/javascript',
    '.png': 'image/png',
    '.json': 'application/json',
    '.unityweb': 'application/octet-stream',
    '.ico': 'image/x-icon',
    '.html': 'text/html'
}

def file_to_base64_data_url(file_path):
    """Convert a file to a Base64-encoded data URL."""
    ext = Path(file_path).suffix.lower()
    mime_type = MIME_TYPES.get(ext, 'application/octet-stream')
    
    with open(file_path, 'rb') as f:
        content = f.read()
    
    b64_content = base64.b64encode(content).decode('utf-8')
    return f'data:{mime_type};base64,{b64_content}'

def process_css(css_content, css_dir):
    """Process CSS to replace image URLs with Base64 data URLs."""
    url_pattern = re.compile(r'url\(\s*[\'"]?([^\'"]+)[\'"]?\s*\)')
    
    def replace_url(match):
        img_path = os.path.join(css_dir, match.group(1))
        return f'url({file_to_base64_data_url(img_path)})' if os.path.exists(img_path) else match.group(0)
    
    return url_pattern.sub(replace_url, css_content)

def process_unity_config(config_path, build_dir):
    """Update Unity .json config to use Base64 data URLs for assets."""
    with open(config_path, 'r', encoding='utf-8') as f:
        config = json.load(f)
    
    # Replace asset URLs with Base64 data URLs
    for key in ['dataUrl', 'asmCodeUrl', 'asmMemoryUrl', 'asmFrameworkUrl', 'wasmCodeUrl', 'wasmFrameworkUrl']:
        if key in config:
            asset_filename = config[key]
            asset_path = os.path.join(build_dir, asset_filename)
            if os.path.exists(asset_path):
                config[key] = file_to_base64_data_url(asset_path)
            else:
                print(f"Warning: Missing asset (skipped): {asset_path}")
    
    return json.dumps(config, indent=2)

def embed_assets_in_html(source_dir, input_html, output_html):
    with open(input_html, 'r', encoding='utf-8') as f:
        html_content = f.read()

    # Track Unity build config for special processing
    unity_config_path = None
    unity_config_data_url = None

    # Process TemplateData and Build directories
    for asset_dir in ['TemplateData', 'Build']:
        dir_path = os.path.join(source_dir, asset_dir)
        if not os.path.isdir(dir_path):
            print(f"Warning: Directory not found: {dir_path}")
            continue

        for root, _, files in os.walk(dir_path):
            for file in files:
                file_path = os.path.join(root, file)
                rel_path = os.path.relpath(file_path, source_dir).replace(os.sep, '/')

                # Special handling for Unity build config (.json)
                if asset_dir == 'Build' and file.endswith('.json'):
                    unity_config_path = rel_path
                    # Process config to embed asset data URLs
                    processed_config = process_unity_config(file_path, root)
                    unity_config_data_url = f"data:application/json;base64,{base64.b64encode(processed_config.encode('utf-8')).decode('utf-8')}"
                    continue  # Skip normal replacement; handle later

                # Embed CSS with image processing
                if file.endswith('.css'):
                    with open(file_path, 'r', encoding='utf-8') as f:
                        css_content = process_css(f.read(), root)
                    css_data_url = f"data:text/css;base64,{base64.b64encode(css_content.encode('utf-8')).decode('utf-8')}"
                    html_content = html_content.replace(rel_path, css_data_url)
                
                # Embed other assets (JS, images, etc.)
                else:
                    data_url = file_to_base64_data_url(file_path)
                    html_content = html_content.replace(rel_path, data_url)

    # Replace Unity config reference with processed data URL
    if unity_config_path and unity_config_data_url:
        html_content = html_content.replace(unity_config_path, unity_config_data_url)
    else:
        print("Error: Unity build config not found - cannot resolve asset URLs")

    with open(output_html, 'w', encoding='utf-8') as f:
        f.write(html_content)
    print(f"Successfully generated embedded HTML: {output_html}")

if __name__ == "__main__":
    embed_assets_in_html(
        source_dir="./",
        input_html="index.html",
        output_html="index_embedded.html"
    )
